package com.blue.rpc.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.blue.core.util.ExceptionUtil;
import com.blue.core.util.JsonUtil;
import com.blue.rpc.core.message.RpcRequest;
import com.blue.rpc.core.message.RpcResponse;

/**
 * RPC服务器工具类
 * 
 * @author zhengj
 * @since 1.0 2017年3月13日
 */
public class RpcServerUtil
{
	private static Logger logger = LoggerFactory.getLogger(RpcServerUtil.class);
	
	private RpcServerUtil()
	{
	}
	
	/**
	 * 创建RPC响应对象
	 * 
	 * @param request RPC请求
	 * @return RPC响应
	 */
	public static RpcResponse create(RpcRequest request)
	{
		if (request == null)
			return null;
		
		RpcResponse response = new RpcResponse();
		response.setMajorVer(request.getMajorVer());
		response.setMinorVer(request.getMinorVer());
		response.setRequestId(request.getRequestId());
		response.setType(request.getType());
		return response;
	}
	
	/**
	 * 判断是否握手报文
	 * 
	 * @param object 报文
	 * @return true是握手报文，false不是握手报文
	 */
	public static boolean isShake(Object object)
	{
		if (object instanceof RpcRequest)
		{
			RpcRequest request = (RpcRequest)object;
			return request.getType() == RpcConst.SHAKE;
		}
		else if (object instanceof RpcResponse)
		{
			RpcResponse response = (RpcResponse)object;
			return response.getType() == RpcConst.SHAKE;
		}
		return false;
	}
	
	/**
	 * 判断是否心跳报文
	 * 
	 * @param object 报文
	 * @return true是心跳报文，false不是心跳报文
	 */
	public static boolean isHeartbeat(Object object)
	{
		if (object instanceof RpcRequest)
		{
			RpcRequest request = (RpcRequest)object;
			return request.getType() == RpcConst.HEARTBEAT;
		}
		else if (object instanceof RpcResponse)
		{
			RpcResponse response = (RpcResponse)object;
			return response.getType() == RpcConst.HEARTBEAT;
		}
		return false;
	}
	
	/**
	 * 写日志
	 * 
	 * @param request 请求对象
	 * @param response 响应对象
	 * @param start 开始时间戳
	 */
	public static void log(RpcRequest request, RpcResponse response, long start)
	{
		long used = System.currentTimeMillis() - start;
		if (response.getException() == null) // 调用成功
		{
			logger.info("service: {}, method: {}, result: 成功, used: {}ms\n请求：{}\n返回: {}", request.getService(), request.getMethod(),
					used, JsonUtil.output(request.getParams()), JsonUtil.output(response.getResult()));
		}
		else if (response.getException() instanceof RpcException) // 业务异常
		{
			logger.info("service: {}, method: {}, result: 失败, used: {}ms\n请求：{}\n异常: {}", request.getService(), request.getMethod(),
					used, JsonUtil.output(request.getParams()), response.getException());
		}
		else // 未知异常
		{
			logger.info("service: {}, method: {}, result: 失败, used: {}ms\n请求：{}\n异常: {}", request.getService(), request.getMethod(),
					used, JsonUtil.output(request.getParams()), ExceptionUtil.exceptionToString(response.getException(), 20));
		}
	}
	
}
